﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcMovie.Models;
using MvcMovie.Util;
using NHibernate;


namespace MvcMovie.Repositories
{
    public class MovieRepository
    {
        private ISession session;

        public MovieRepository()
        {
            this.session = MvcMovie.Util.NHibernateUtil.GetSession();
        }

        ~MovieRepository()
        {
            session.Close();
        }

        public void AddMovie(Movie movie)
        {
                using (var transaction = session.BeginTransaction())
                {
                    session.Save(movie);
                    transaction.Commit();
                }
        }

        public Movie UpdateMovie(Movie movie)
        {
            
            using (var transaction = session.BeginTransaction())
            {
                session.Merge(movie);
                transaction.Commit();
            }

            return movie;
        }

        public void Delete(Movie movie)
        {
            using (var transaction = session.BeginTransaction())
            {
                session.Delete(movie);
                transaction.Commit();
            }
        }

        public IEnumerable<Movie> GetAll()
        {
            return this.session.QueryOver<Movie>().List<Movie>();
        }

        public Movie GetById(int id)
        {
            var movie = (Movie) session.Get(new Movie().GetType(), id);

            return movie;
        }
    }
}